package com.ruoyi.pingan.fymodule.goodsinfo.goodscategoryjoin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.pingan.enums.CommonSortOrderEnum;
import com.ruoyi.pingan.exception.CommonException;
import com.ruoyi.pingan.fymodule.goodsinfo.goodscategoryjoin.entity.SxoGoodsCategoryJoin;
import com.ruoyi.pingan.fymodule.goodsinfo.goodscategoryjoin.mapper.SxoGoodsCategoryJoinMapper;
import com.ruoyi.pingan.fymodule.goodsinfo.goodscategoryjoin.param.SxoGoodsCategoryJoinAddParam;
import com.ruoyi.pingan.fymodule.goodsinfo.goodscategoryjoin.param.SxoGoodsCategoryJoinEditParam;
import com.ruoyi.pingan.fymodule.goodsinfo.goodscategoryjoin.param.SxoGoodsCategoryJoinIdParam;
import com.ruoyi.pingan.fymodule.goodsinfo.goodscategoryjoin.param.SxoGoodsCategoryJoinPageParam;
import com.ruoyi.pingan.fymodule.goodsinfo.goodscategoryjoin.service.SxoGoodsCategoryJoinService;
import com.ruoyi.pingan.page.CommonPageRequest;
import com.ruoyi.pingan.util.CommonDownloadUtil;
import com.ruoyi.pingan.util.CommonResponseUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 商品分类关联Service接口实现类
 *
 * @author wangy
 * @date  2025/07/25 16:48
 **/
@Service
public class SxoGoodsCategoryJoinServiceImpl extends ServiceImpl<SxoGoodsCategoryJoinMapper, SxoGoodsCategoryJoin> implements SxoGoodsCategoryJoinService {

    @Override
    public Page<SxoGoodsCategoryJoin> page(SxoGoodsCategoryJoinPageParam sxoGoodsCategoryJoinPageParam) {
        QueryWrapper<SxoGoodsCategoryJoin> queryWrapper = new QueryWrapper<SxoGoodsCategoryJoin>().checkSqlInjection();
        if(ObjectUtil.isAllNotEmpty(sxoGoodsCategoryJoinPageParam.getSortField(), sxoGoodsCategoryJoinPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(sxoGoodsCategoryJoinPageParam.getSortOrder());
            queryWrapper.orderBy(true, sxoGoodsCategoryJoinPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(sxoGoodsCategoryJoinPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SxoGoodsCategoryJoin::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SxoGoodsCategoryJoinAddParam sxoGoodsCategoryJoinAddParam) {
        SxoGoodsCategoryJoin sxoGoodsCategoryJoin = BeanUtil.toBean(sxoGoodsCategoryJoinAddParam, SxoGoodsCategoryJoin.class);
        this.save(sxoGoodsCategoryJoin);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SxoGoodsCategoryJoinEditParam sxoGoodsCategoryJoinEditParam) {
        SxoGoodsCategoryJoin sxoGoodsCategoryJoin = this.queryEntity(sxoGoodsCategoryJoinEditParam.getId());
        BeanUtil.copyProperties(sxoGoodsCategoryJoinEditParam, sxoGoodsCategoryJoin);
        this.updateById(sxoGoodsCategoryJoin);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SxoGoodsCategoryJoinIdParam> sxoGoodsCategoryJoinIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(sxoGoodsCategoryJoinIdParamList, SxoGoodsCategoryJoinIdParam::getId));
    }

    @Override
    public SxoGoodsCategoryJoin detail(SxoGoodsCategoryJoinIdParam sxoGoodsCategoryJoinIdParam) {
        return this.queryEntity(sxoGoodsCategoryJoinIdParam.getId());
    }



    @Override
    public void downloadImportTemplate(HttpServletResponse response) throws IOException {
       File tempFile = null;
       try {
         List<SxoGoodsCategoryJoinEditParam> dataList = CollectionUtil.newArrayList();
         String fileName = "商品分类关联导入模板_" + DateUtil.format(DateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".xlsx";
         tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
         EasyExcel.write(tempFile.getPath(), SxoGoodsCategoryJoinEditParam.class).sheet("商品分类关联").doWrite(dataList);
         CommonDownloadUtil.download(tempFile, response);
       } catch (Exception e) {
         log.error(">>> 商品分类关联导入模板下载失败：", e);
         CommonResponseUtil.renderError(response, "商品分类关联导入模板下载失败");
       } finally {
         FileUtil.del(tempFile);
       }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject importData(MultipartFile file) {
        try {
            int successCount = 0;
            int errorCount = 0;
            JSONArray errorDetail = JSONUtil.createArray();
            // 创建临时文件
            File tempFile = FileUtil.writeBytes(file.getBytes(), FileUtil.file(FileUtil.getTmpDir() +
                    FileUtil.FILE_SEPARATOR + "sxoGoodsCategoryJoinImportTemplate.xlsx"));
            // 读取excel
            List<SxoGoodsCategoryJoinEditParam> sxoGoodsCategoryJoinEditParamList =  EasyExcel.read(tempFile).head(SxoGoodsCategoryJoinEditParam.class).sheet()
                    .headRowNumber(1).doReadSync();
            List<SxoGoodsCategoryJoin> allDataList = this.list();
            for (int i = 0; i < sxoGoodsCategoryJoinEditParamList.size(); i++) {
                JSONObject jsonObject = this.doImport(allDataList, sxoGoodsCategoryJoinEditParamList.get(i), i);
                if(jsonObject.getBool("success")) {
                    successCount += 1;
                } else {
                    errorCount += 1;
                    errorDetail.add(jsonObject);
                }
            }
            return JSONUtil.createObj()
                    .set("totalCount", sxoGoodsCategoryJoinEditParamList.size())
                    .set("successCount", successCount)
                    .set("errorCount", errorCount)
                    .set("errorDetail", errorDetail);
        } catch (Exception e) {
            log.error(">>> 商品分类关联导入失败：", e);
            throw new CommonException("商品分类关联导入失败");
        }
    }

    public JSONObject doImport(List<SxoGoodsCategoryJoin> allDataList, SxoGoodsCategoryJoinEditParam sxoGoodsCategoryJoinEditParam, int i) {
        String id = sxoGoodsCategoryJoinEditParam.getId();
        if(ObjectUtil.hasEmpty(id)) {
            return JSONUtil.createObj().set("index", i + 1).set("success", false).set("msg", "必填字段存在空值");
        } else {
            try {
                int index = CollStreamUtil.toList(allDataList, SxoGoodsCategoryJoin::getId).indexOf(sxoGoodsCategoryJoinEditParam.getId());
                SxoGoodsCategoryJoin sxoGoodsCategoryJoin;
                boolean isAdd = false;
                if(index == -1) {
                    isAdd = true;
                    sxoGoodsCategoryJoin = new SxoGoodsCategoryJoin();
                } else {
                    sxoGoodsCategoryJoin = allDataList.get(index);
                }
                BeanUtil.copyProperties(sxoGoodsCategoryJoinEditParam, sxoGoodsCategoryJoin);
                if(isAdd) {
                    allDataList.add(sxoGoodsCategoryJoin);
                } else {
                    allDataList.remove(index);
                    allDataList.add(index, sxoGoodsCategoryJoin);
                }
                this.saveOrUpdate(sxoGoodsCategoryJoin);
                return JSONUtil.createObj().set("success", true);
            } catch (Exception e) {
              log.error(">>> 数据导入异常：", e);
              return JSONUtil.createObj().set("success", false).set("index", i + 1).set("msg", "数据导入异常");
            }
        }
    }

    @Override
    public SxoGoodsCategoryJoin queryEntity(String id) {
        SxoGoodsCategoryJoin sxoGoodsCategoryJoin = this.getById(id);
        if(ObjectUtil.isEmpty(sxoGoodsCategoryJoin)) {
            throw new CommonException("商品分类关联不存在，id值为：{}", id);
        }
        return sxoGoodsCategoryJoin;
    }

    @Override
    public void exportData(List<SxoGoodsCategoryJoinIdParam> sxoGoodsCategoryJoinIdParamList, HttpServletResponse response) throws IOException {
       File tempFile = null;
       try {
         List<SxoGoodsCategoryJoinEditParam> dataList;
         if(ObjectUtil.isNotEmpty(sxoGoodsCategoryJoinIdParamList)) {
            List<String> idList = CollStreamUtil.toList(sxoGoodsCategoryJoinIdParamList, SxoGoodsCategoryJoinIdParam::getId);
            dataList = BeanUtil.copyToList(this.listByIds(idList), SxoGoodsCategoryJoinEditParam.class);
         } else {
            dataList = BeanUtil.copyToList(this.list(), SxoGoodsCategoryJoinEditParam.class);
         }
         String fileName = "商品分类关联_" + DateUtil.format(DateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".xlsx";
         tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
         EasyExcel.write(tempFile.getPath(), SxoGoodsCategoryJoinEditParam.class).sheet("商品分类关联").doWrite(dataList);
         CommonDownloadUtil.download(tempFile, response);
       } catch (Exception e) {
         log.error(">>> 商品分类关联导出失败：", e);
         CommonResponseUtil.renderError(response, "商品分类关联导出失败");
       } finally {
         FileUtil.del(tempFile);
       }
    }
}
